package com.uxsino.simo.query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.uxsino.commons.utils.config.PropElement;
import com.uxsino.reactorq.model.IndicatorValue;
import com.uxsino.simo.indicator.ListIndicator;
import com.uxsino.simo.utils.ConfigLoadingContext;

public class UnionQueryCombine extends QueryCombine<ListIndicator, List<Map<String, Object>>> {

    public UnionQueryCombine(ListIndicator resultIndicator) {
        super(resultIndicator);
    }

    @Override
    public List<Map<String, Object>> apply(QueryContext ctxt, List<IndicatorValue> lists) {

        // List<Map<String, Object>> r = new ArrayList<>();

        List<Map<String, Object>> subQueryResults = new ArrayList<>();
        List<Map<String, Object>> qResults = new ArrayList<>();

        Map<String, Object> variables = new HashMap<>();

        lists.forEach(v -> {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> l = (List<Map<String, Object>>) v.value;

            if (l != null)
                subQueryResults.addAll(l);
        });

        for (Map<String, Object> listValue : subQueryResults) {
            for (Map.Entry<String, Object> entry : listValue.entrySet()) {
                Object value = entry.getValue();
                if (value != null || !variables.containsKey(entry.getKey())) {
                    variables.put(entry.getKey(), value);
                }
            }
        }
        qResults.add(variables);

        return qResults;
    }

    @Override
    public void loadProp(PropElement eCombine, ConfigLoadingContext lctxt) {

    }

    @Override
    public boolean isCustom() {
        return false;
    }

}
